﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 补充货物
/// </summary>
public class AddGoodsController : MonoSingleton<AddGoodsController>
{
    /*
     游戏规则  随机三大类中的一种进行补充， 摄像机移动到此货架，再随机1 到 3 种 此分类的物品进行补充；
     装货的补充篮里面也对应有一到三种此分类物品，其他的用其他随机的分类物品替代
         */
    //货物分类区 坐标存储
    Transform vegetablesPoint;
    Transform fruitsUpPoint;
    Transform fruitsDownPoint;
    Transform snacksPoint;

    Transform cars;

    // 存储的都是表的 resid
    List<string> datalist = new List<string>();

    //货物储存区  存储货物resid
    List<string> goodsList = new List<string>();

    //需要补充的货物 GameObject
    List<GameObject> addGoodsList = new List<GameObject>();

    //随机种类 一个种类物品 进行补充
    GoodsType goodsType;

    //随机数量  一到三个物品 补充 货物
    int addCount;

    //随机的补充货物的位置 point  0 - 5  存放索引 ，水果是 0 - 2
    List<int> poinList = new List<int>();

    //购物车放置的 可以成功拖拽的（当前种类的） 物品   目前是三个, 存放的索引
    int carCount = 3;
    List<int> carList = new List<int>();

    string path;

    Transform parent;

    //GameObject effect;

    GameObject successEffect;

    //TRSController trs;
    //是否清理物品
    public bool isClearGoods = false;
    protected override void Awake()
    {
        vegetablesPoint = transform.Find("vegetables");
        fruitsUpPoint = transform.Find("fruitsUp");
        fruitsDownPoint = transform.Find("fruitsDown");
        snacksPoint = transform.Find("snacks");

        cars = transform.Find("cars");

        //effect = transform.Find("502004014").gameObject;

        successEffect = transform.Find("502004088").gameObject;

        //trs = transform.Find("Hand_Click").GetComponent<TRSController>();

        //========== mjbTest
        //StartGame();
    }
    
    /// <summary>
    /// 随机大的种类
    /// </summary>
    void RandomBigType()
    {
        //随机种类 一个种类物品 进行补充
        goodsType = (GoodsType)Random.Range(1, 4);
        //goodsType = (GoodsType)1;
        if(isClearGoods)
            PlaceGoods.Instance.ClearGoodsType(goodsType);
        switch (goodsType)
        {
            case GoodsType.Vegetables:
                SuperMarketGame.Instance.superCamera.transform.position = new Vector3(-7.55f, 2.45f, 7.09f);
                cars.transform.localPosition = new Vector3(-7.633f, 0, 0);
                //effect.transform.localPosition = new Vector3(-8.13f, 0, 0);
                successEffect.transform.localPosition = new Vector3(-7.53f, 0f, -1.31f);
                datalist = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
                path = SuperMarketResPath.Vegetables_Dir;
                parent = vegetablesPoint;
                break;
            case GoodsType.Fruits:
                SuperMarketGame.Instance.superCamera.transform.position = new Vector3(-11.15f, 2.45f, 7.09f);
                datalist = GoodsInfoModel.Instance.GetItems(GoodsType.Fruits);
                cars.transform.localPosition = new Vector3(-11.25f, 0, 0);
                //effect.transform.localPosition = new Vector3(-11.83f, 0f, 0f);
                successEffect.transform.localPosition = new Vector3(-11.23f, 0f, -1.31f);
                //TODO    水果区 要注意  随机的是上面的  还是下面的 ，如果随机的是上面的，就都上面，随机下面的都随机下面( 补充上面的 )
                //path = SuperMarketResPath.FruitUp_Dir;
                //parent = fruitsUpPoint;
                break;
            case GoodsType.Snacks:
                SuperMarketGame.Instance.superCamera.transform.position = new Vector3(-14.61f, 2.45f, 7.09f);
                cars.transform.localPosition = new Vector3(-14.68f, 0, 0);
                //effect.transform.localPosition = new Vector3(-15.45f, 0, 0);
                successEffect.transform.localPosition = new Vector3(-14.85f, 0f, -1.31f);
                datalist = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
                path = SuperMarketResPath.Snacks_Dir;
                parent = snacksPoint;
                break;
        }
    }
    //TODO 1 、随机出6个resid，其中随机位置 实例化 6-addCount 个 商品放在产品柜台上，  addCount 个商品  随机位置 放入购物车 
    //2  剩下没有被随机放入的购物车，从其他种类商品里 随机 补充
    public void StartGame()
    {
        SuperMarketGame.Instance.soundCtrl.PlaySmallGameSound(GameType.PlaceGoods);
        AddGoodsUIController.Instance.OpenView();
        //随机补充的大类型货物
        RandomBigType();

        //随机数量  一到三个物品 补充 货物
        addCount = Random.Range(1, 4);
        //Debug.Log(addCount + "  ===== addCount ");

        //随机摆放物品 6个都先放在货架上
        if (goodsType != GoodsType.Fruits)
            RandomGoods(goodsList, datalist, path, parent);
        else
        {
            List<string> frulist1 = new List<string>();
            List<string> frulist2 = new List<string>();
            int index = 0;
            foreach (string item in datalist)
            {
                index++;
                if (index < 7)
                    frulist1.Add(item);
                else
                    frulist2.Add(item);
            }
            index = 0;
            //水果的话就是先补充上面的 ，再放下面的
            List<string> fruitsUpList = new List<string>();
            path = SuperMarketResPath.FruitUp_Dir;
            parent = fruitsUpPoint;
            RandomGoods(fruitsUpList, frulist1, path, parent, 3);

            List<string> fruitsDownList = new List<string>();
            path = SuperMarketResPath.FruitDown_Dir;
            parent = fruitsDownPoint;
            RandomGoods(fruitsDownList, frulist2, path, parent, 3);
        }


        //随机的补充货物的位置 point  0 - 5  水果是 0 - 3
        //将随机补充的货物移动到购物车中
        RandomAddGoodsInCar();

        if (carList.Count < carCount)
        {
            //从其他种类商品里 随机 补充 放到购物车中来
            //从其它种类随机 1 或者 2 种
            int num = carCount - carList.Count;
            //Debug.Log(" 从其他种类商品里随机 num ==== " + num);
            RandomCarOtherGoods(num);
        }


        /*
            首次进入游戏，出手指提示指引。玩家操作后，指引消失。
            非首次进入游戏，玩家画面无操作8秒，出语音或物品晃动提示。
         */
        //SuperMarketGame.Instance.addgoodsGameCount = 2;
        if (SuperMarketGame.Instance.addgoodsGameCount == 1)
        {
            //Debug.Log(carList[0] + " ,carList[0] , poinList[0] === " + poinList[0]);
            AddGoodsUIController.Instance.ShowHand(carList[0], parent.GetChild(poinList[0]));
            //trs.gameObject.SetActive(true);
            //trs.transform.localEulerAngles = new Vector3(45f, 0f, 0f);
            //随机的补充货物的位置 point  0 - 5  存放索引 ，水果是 0 - 2            
            //购物车放置的 可以成功拖拽的（当前种类的） 物品   目前是三个, 存放的索引
            //trs.position.form = cars.GetChild(carList[0]).position;        
            //Vector3 handTo = parent.GetChild(poinList[0]).position;
            //trs.position.to = new Vector3(handTo.x, handTo.y, handTo.z + 1f);
            //trs.position.loop = true;
        }
        else
        {
            HideHand();
            //trs.gameObject.SetActive(false);
            isShakeUI = true;
            AddGoodsUIController.Instance.ShakeUI(strength);
            //totalCount = 8f;
        }
    }

    public bool isShakeUI = false;
    float interval = 10f;
    float totalCount = 0f;
    public float strength = 15f;
    private void Update()
    {
        if (isShakeUI)
        {
            totalCount += Time.deltaTime;
            if (totalCount >= interval)
            {
                SuperMarketGame.Instance.soundCtrl.PlaySmallGameSound(GameType.PlaceGoods);
                AddGoodsUIController.Instance.ShakeUI(strength);
                totalCount = 0;
            }
        }

    }
    public void HideHand()
    {
        /*if (trs != null)
        {
            trs.position.loop = false;
            trs.gameObject.SetActive(false);
        }*/
        AddGoodsUIController.Instance.CloseHand();
    }


    public void PlayEffect()
    {
        findCount++;
        //播放特效
        //Debug.Log(findCount);
        if (findCount >= addCount)
        {
            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_604050102);
            //effect.SetActive(true);
            successEffect.SetActive(true);
            ParticleSystem ps = successEffect.transform.GetChild(0).GetComponent<ParticleSystem>();
            if (!ps.isPlaying)
                ps.Play();
            SuperMarketGame.Instance.soundCtrl.PlayLeDiVoiceAnimation(SuperMarketResPath.Sound_404050405);
            //TODO    EndGame   
            StartCoroutine(TimeUtility.DelayInvoke(2.5f, () =>
            {
                Debug.Log("  结束整理 ");
                EndGame();
            }));

        }
    }
    int findCount = 0;
    public void EndGame()
    {
        findCount = 0;
        SuperMarketGame.Instance.gameCount = 0;
        SuperMarketGame.Instance.OnReset(TransitionType.Cloud,()=> {
            //effect.SetActive(false);
            successEffect.SetActive(false);
        }, () =>
        {

            AddGoodsUIController.Instance.CloseView();
            Destroy(gameObject);
        });
    }

    //从其他种类商品随机  随机的数量
    void RandomCarOtherGoods(int num)
    {
        List<string> listCar;

        GameObject go;
        List<string> friutListCar;
        List<string> frulist1;
        int index = 0;
        Transform carParent;
        int carIndex = 0; 
        switch (goodsType)
        {
            case GoodsType.Vegetables:
                friutListCar = GoodsInfoModel.Instance.GetItems(GoodsType.Fruits);
                frulist1 = new List<string>();
                index = 0;
                foreach (string item in friutListCar)
                {
                    index++;
                    if (index < 7)
                        frulist1.Add(item);
                }
                if (num == 1)
                {
                    if (Random.Range(0, 2) == 0)
                    {
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(frulist1, SuperMarketResPath.FruitUp_Dir, carParent, carIndex);
                    }
                    else
                    {
                        listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(listCar, SuperMarketResPath.Snacks_Dir, carParent, carIndex);
                    }
                }
                else
                {
                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(frulist1, SuperMarketResPath.FruitUp_Dir, carParent, carIndex);

                    listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(listCar, SuperMarketResPath.Snacks_Dir, carParent, carIndex);
                }
                break;
            case GoodsType.Fruits:
                if (num == 1)
                {
                    if (Random.Range(0, 2) == 0)
                    {
                        listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(listCar, SuperMarketResPath.Vegetables_Dir, carParent, carIndex);
                    }
                    else
                    {
                        listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(listCar, SuperMarketResPath.Snacks_Dir, carParent, carIndex);
                    }
                }
                else
                {
                    listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(listCar, SuperMarketResPath.Vegetables_Dir, carParent, carIndex);

                    listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Snacks);
                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(listCar, SuperMarketResPath.Snacks_Dir, carParent, carIndex);
                }
                break;
            case GoodsType.Snacks:
                friutListCar = GoodsInfoModel.Instance.GetItems(GoodsType.Fruits);
                frulist1 = new List<string>();
                index = 0;
                foreach (string item in friutListCar)
                {
                    index++;
                    if (index < 7)
                        frulist1.Add(item);
                }
                if (num == 1)
                {
                    if (Random.Range(0, 2) == 0)
                    {
                        listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(listCar, SuperMarketResPath.Vegetables_Dir, carParent, carIndex);
                    }
                    else
                    {
                        carParent = FindCarParent(ref carIndex);
                        RandomOneGoods(frulist1, SuperMarketResPath.FruitUp_Dir, carParent, carIndex);
                    }
                }
                else
                {
                    listCar = GoodsInfoModel.Instance.GetItems(GoodsType.Vegetables);
                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(listCar, SuperMarketResPath.Vegetables_Dir, carParent, carIndex);

                    carParent = FindCarParent(ref carIndex);
                    RandomOneGoods(frulist1, SuperMarketResPath.FruitUp_Dir, carParent, carIndex);
                }
                break;            
        }
    }

    Transform FindCarParent(ref int carIndex)
    {
        Transform parent = cars;
        for (int i = 0; i < cars.childCount; i++)
        {
            if (cars.GetChild(i).childCount == 0)
            {
                carIndex = i;
                return cars.GetChild(i);
            }
        }
        return parent;
    }

    GameObject RandomOneGoods(List<string> dataOrgList, string _path, Transform _parent, int carIndex)
    {
        int temp = Random.Range(0, dataOrgList.Count);
        TableProto.SuperMarketGoodsInfo smgi = GoodsInfoModel.Instance.GetModelByResId(dataOrgList[temp]);
        string groupResId = smgi.groupId;
        //刷新UI
        AddGoodsUIController.Instance.Refresh(smgi.atlas, carIndex);
        string resPath = _path + "/" + groupResId;
        Debug.Log(resPath + "  === resPath ");
        GameObject veg = Instantiate(CommonUtility.LoadPrefab(resPath));
        veg.transform.SetParent(_parent);
        veg.transform.localPosition = Vector3.zero;
        veg.transform.localRotation = Quaternion.identity;

        DragAddGoods dag = veg.AddComponent<DragAddGoods>();
        dag.isTarget = false;

        return veg;
    }

    /// <summary>
    /// 随机生成补充的货物 并移动到购物车中
    /// </summary>
    void RandomAddGoodsInCar()
    {
        //随机一个位置出来，将物品 放入到购车中里
        while (poinList.Count < addCount)
        {
            int temp = 0;
            if (goodsType == GoodsType.Fruits)
            {
                temp = Random.Range(0, 3);
                parent = fruitsUpPoint;
            }
            else
                temp = Random.Range(0, 6);
            if (!poinList.Contains(temp))
            {
                poinList.Add(temp);

                int tempIndex = Random.Range(0, carCount);
                while (carList.Contains(tempIndex))
                {
                    tempIndex = Random.Range(0, carCount);
                }
                carList.Add(tempIndex);

                Transform tempgoods = parent.GetChild(temp).GetChild(0);
                tempgoods.SetParent(cars.GetChild(tempIndex));

                TableProto.SuperMarketGoodsInfo smgi = GoodsInfoModel.Instance.GetModelByResId(tempgoods.GetChild(0).name);
                //刷新UI
                AddGoodsUIController.Instance.Refresh(smgi.atlas, tempIndex);

                tempgoods.localPosition = Vector3.zero;
                tempgoods.localRotation = Quaternion.identity;
                DragAddGoods dag = tempgoods.gameObject.AddComponent<DragAddGoods>();
                dag.isTarget = true;
            }
        }
    }


    /// <summary>
    /// 随机摆放的物品和随机需要补充无物品(不重复)
    /// </summary>
    /// <param name="listPlace">随机到的物品 goods</param>
    /// <param name="listGoods">随机的物品 数据</param>
    /// <param name="path">Res路径</param>
    /// <param name="parent">父级</param>
    /// <param name="count">随机数量</param>
    void RandomGoods(List<string> listPlace, List<string> listGoods, string _path, Transform _parent, int count = 6)
    {
        while (listPlace.Count < count)
        {
            int temp = Random.Range(0, listGoods.Count);
            //print(temp + "  listGoods.Count == "+ listGoods.Count);         
            if (!listPlace.Contains(listGoods[temp]))
            {
                listPlace.Add(listGoods[temp]);

                string groupResId = GoodsInfoModel.Instance.GetModelByResId(listGoods[temp]).groupId;
                //摆放的是Group 组物品
                string resPath = path + "/" + groupResId;
                //Debug.Log(resPath);
                GameObject veg = Instantiate(CommonUtility.LoadPrefab(resPath));
                //Debug.Log(listPlace.Count-1 + "  == parent.name === "+ parent.name);
                veg.transform.SetParent(parent.GetChild(listPlace.Count - 1));
                veg.transform.localPosition = Vector3.zero;
                veg.transform.localRotation = Quaternion.identity;

            }
            if (listPlace.Count == count)
                break;
        }
    }

}

